package com.dbt.admin.controller;

import com.dbt.admin.domain.entity.SysUser;
import com.dbt.admin.domain.vo.LoginVo;
import com.dbt.admin.exception.UserTooManyException;
import com.dbt.admin.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

/**
 * @author fangkun
 * @create 2022-08-15-14:53
 */
@Slf4j
@Controller
public class IndexController {

    @Autowired
    LoginService loginService;

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("/login")
    public String main(LoginVo loginVo, HttpSession session, Model model){

        String userName = loginVo.getUserName();
        String password = loginVo.getPassword();

        SysUser user = loginService.selectUser(userName,password);

        if(user != null) {
            //把登陆成功的用户保存起来
            session.setAttribute("loginUser",user);

            redisTemplate.opsForValue().set("loginUser",user);

            //登录成功重定向到main.html;  重定向防止表单重复提交
            return "redirect:/main.html";
        } else {
            model.addAttribute("msg","用户不存在");
            //回到登录页面
            return "login";
        }

    }

    @GetMapping(value = {"/","/login"})
    public String loginPage(){
        return "login";
    }

    @GetMapping("/main.html")
    public String mainPage(HttpSession session,Model model){
        return "main";
    }

    @GetMapping("/responsive_table")
    public String responsive_table(){
        return "table/responsive_table";
    }

    @GetMapping("/editable_table")
    public String editable_table(){
        return "table/editable_table";
    }

    @GetMapping("/dynamic_table")
    public String dynamic_table(Model model){

//        List<LoginVo> users = Arrays.asList(
//                new LoginVo("zhangsan","123456"),
//                new LoginVo("lisi","123456")
//        );
//        model.addAttribute("users",users);
//
//        if(users.size()>1){
//            throw new UserTooManyException();
//        }

//        Object loginUser = redisTemplate.opsForValue().get("loginUser");

        return "table/dynamic_table";
    }

    @GetMapping("/basic_table")
    public String basic_table(){

//        int i = 10/0;

        return "table/basic_table";
    }

    @GetMapping("/pricing_table")
    public String pricing_table(){
        return "table/pricing_table";
    }

    @GetMapping("/form_layouts")
    public String form_layouts(){
        return "form/form_layouts";
    }

}
